import Vue from 'vue'
import Vuex from 'vuex'
import {
    checkMusic,
    getCatList,
    getCountryList,
    getMusicInfo,
    getUserAccountInfo,
    userLogout
} from "@/http";
import {removeCookie} from "@/http/tools";

Vue.use(Vuex)
/**
 * 获取单独一首歌的url
 * @param songId    歌曲id
 * @param playingLevel  播放质量
 * @param callBack  获取之后的回调函数
 */
const getSingleMusic = (songId, playingLevel, callBack) => {
    Promise.all([getMusicInfo(songId, playingLevel), checkMusic(songId)]).then(res => {
        const [music, musicAuthority] = res
        const {code, data} = music
        if (code === 200) {
            // 格式化得到的音乐详细信息
            const formatMusic = data.map(item => {
                return {
                    id: item.id,
                    url: item.url
                }
            })
            // 只请求了一首歌的url
            callBack({
                ...formatMusic[0],
                ...musicAuthority
            })
        }
    })
}
const actions = {
    storageUserInfo(context, value) {
        context.commit('StorageUserInfo', value)
    },
    // 更新当前音乐播放列表
    updatePlaySongList(context, musicInfo) {
        // type:0歌单,1专辑，listId:专辑或歌单id,songId:当前需要播放的歌曲id,isUpdatePlayingList是否更新列表
        const {songId} = musicInfo
        // 当前列表显示的歌曲
        const {curPlayingLevel} = context.state
        // 获取当前播放歌曲的信息
        getSingleMusic(songId, curPlayingLevel, curPlayingSong => {
            // 将处理提交到mutations中更新
            context.commit('UpdatePlaySongList', {
                musicInfo,
                curPlayingSong
            })
        })
    },
    // 请求发现页的标签分类
    getExplorePageCatList(context) {
        getCatList().then(res => {
            const {code, all, sub, categories} = res
            const {name, type, category, hot} = all
            const {single} = context.getters.curCandidateList
            if (code === 200) {
                // 先把全部歌单和官方类别放入
                const tagList = [{
                    level: 0,
                    name,
                    type,
                    category,
                    hot,
                    limit: 30,
                    offset: 0,
                }, {
                    level: single.length + 1,
                    name: '官方',
                    limit: 30,
                    offset: 0
                }]
                const subArr = sub.map((item, index) => {
                    return {
                        level: single.length + 2 + index,
                        name: item.name,
                        type: item.type,
                        category: item.category,
                        hot: item.hot,
                        limit: 30,
                        offset: 0
                    }
                })
                tagList.push(...subArr)
                context.commit('GetExplorePageCatList', {
                    tagList,
                    categories
                })
            }
        }, err => {
            console.log(`类别加载失败：${err}`)
        })
    },
    // 获取每个国家的区号
    getLoginCountryList(context) {
        getCountryList().then(res => {
            const {code, data} = res
            const result = []
            if (code === 200) {
                // 遍历数组
                for (const datum of data) {
                    const {label, countryList} = datum
                    result.push(...countryList.map(item => {
                        return {
                            ...item,
                            showCode: `+${item.code}`
                        }
                    }))
                }
                context.commit('GetLoginCountryList', result)
            }
        }, err => {
            console.log(err)
        })
    },
    // 获取用户数据
    fetchUserProfile(context) {
        getUserAccountInfo().then(res => {
            const {profile} = res
            context.commit('UpdateData', {key: 'userProfile', value: profile})
        })
    },
    unLogin(context) {
        userLogout().then(res => {
            const {code} = res
            if (code === 200) {
                context.commit('UpdateData', {key: 'userProfile', value: undefined})
                removeCookie('MUSIC_U')
            }
        })
    }
}
const mutations = {
    StorageUserInfo(state, value) {
        state.userInfo = value
    },
    UpdatePlaySongList(state, data) {
        const {curPlayingSong, musicInfo} = data
        const {songId, isUpdatePlayingList} = musicInfo
        if (isUpdatePlayingList) {
            // 如果要更新当前播放列表就把当前歌单中的歌曲更新到playingSongList中
            state.playingSongList = state.songList
        }
        // 在播放列表中找到正在播放的歌曲
        const music = state.playingSongList.playList.filter(item => {
            return item.id === songId
        })[0]
        state.curPlayingMusic = {
            ...curPlayingSong,
            ...music
        }
        // // 移除当前正在播放的歌曲
        // state.playingSongList.playList = state.playingSongList.playList.filter(item => {
        //     return item.id !== songId
        // })
        // // 更新已经播放歌曲的数量
        // state.playingSongList.hasPlayNum = state.songList.playList.length - state.playingSongList.playList.length
    },
    // 候选播放列表
    UpdateSongList(state, data) {
        state.songList = data
    },
    GetExplorePageCatList(state, data) {
        const {tagList, categories} = data
        state.tagList = tagList
        state.categories = categories
    },
    /**
     * 是否显示底部的音乐播放栏
     * @param state
     * @param flag
     * @constructor
     */
    ShowBottomPlayer(state, flag) {
        state.isShowBottom = flag
    },
    GetLoginCountryList(state, data) {
        state.countryList = [...data]
    },
    // 更新数据
    UpdateData(state, {key, value}) {
        state[key] = value
    }
}

const state = {
    // 底部音乐播放器是否显示
    isShowBottom: true,
    // 用户信息
    userInfo: {},
    // 当前播放音乐的质量
    curPlayingLevel: 'standard',
    // 正在播放的音乐
    curPlayingMusic: {
        id: -1,
        url: '',
        albumName: '',
        musicName: '',
        time: 0,
        success: true,
        message: 'ok',
        picUrl: '',
        singers: [],
        alia: []
    },
    // 当前播放音乐列表（乱序）
    playingSongList: {
        // 用来标识当前播放列表是否与播放的歌所在的列表一致
        id: -1,
        type: -1,
        playList: [],
        // 已经播放的音乐的数量
        hasPlayNum: 0
    },
    // 当前在页面中显示的播放列表（顺序）
    songList: {
        // 用来标识当前播放列表是否与播放的歌所在的列表一致
        id: -1,
        type: -1,
        playList: []
    },
    // 所有标签列表
    tagList: [],
    // category对应的值
    categories: {},
    // mv播放器的设置
    mvSettings: {
        volume: 1
    },
    // 歌手类型
    singerType: [
        {
            name: '全部',
            level: -1
        },
        {
            name: '男',
            level: 1
        },
        {
            name: '女',
            level: 2
        },
        {
            name: '乐队',
            level: 3
        }
    ],
    // 歌手地区
    singerArea: [
        {
            name: '全部',
            level: -1
        },
        {
            name: '华语',
            level: 7
        },
        {
            name: '欧美',
            level: 96
        },
        {
            name: '日本',
            level: 8
        },
        {
            name: '韩国',
            level: 16
        },
        {
            name: '其他',
            level: 0
        }
    ],
    // 国家区号
    countryList: [],
    userProfile: {}
}

const getters = {
    // 发现页面显示的标签
    curCandidateList(state) {
        const {tagList} = state
        const curCandidateList = {
            single: [{
                level: 1,
                name: '推荐歌单',
                url: '/personalized',
                limit: 30,
                isShow: true,
                isCheck: false
            }, {
                level: 2,
                name: '精品歌单',
                url: '/top/playlist/highquality',
                before: 0,
                limit: 30,
                isShow: true,
                isCheck: false
            }, {
                level: 3,
                name: '排行榜',
                url: '/toplist',
                isShow: true,
                isCheck: false
            }]
        }
        if (tagList.length) {
            curCandidateList['sameUrl'] = {
                url: '/top/playlist',
                // new/hot
                order: 'new',
                list: [...tagList]
            }
        }
        return curCandidateList
    },
    // 歌手的名字按字母筛选
    singerName(state) {
        const res = [{
            name: '全部',
            level: '-1'
        }]
        for (let i = 65; i <= 90; i++) {
            const name = {
                name: String.fromCharCode(i),
                level: String.fromCharCode(i).toLowerCase()
            }
            res.push(name);
        }
        res.push({
            name: '#',
            level: '0'
        })
        return res
    }
}
export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})